
<template>
  <el-dialog v-model="showDialog" :title="drawerTitile" :close-on-click-modal="true" :destroy-on-close="destroyOnClose"
    @close="clean">
    <div class="formDrawer">

      <el-form ref="formRef" :rules="rules" :model="formData.value" label-width="80px" size="small">
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入角色名称" v-model="formData.value.roleName"></el-input>
        </el-form-item>
        <el-form-item label="是否可用" prop="status">
          <el-radio-group v-model="formData.value.status">
            <el-radio :label="true" size="large" border>可用</el-radio>
            <el-radio :label="false" size="large" border>不可用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div class="actions">
        <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
        <el-button type="default" @click="close">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, computed, reactive, toRef } from "vue"
import {
  toast
} from '~/composables/util.js'
import Role from '~/api/role.js'

const showDialog = ref(false)
const props = defineProps({
  destroyOnClose: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object, // 假设初始值是一个对象
    default: () => ({}) // 默认为空对象
  },
  drawerTitile: {
    type: String,
    default: '修改'
  }

})

const loading = ref(false)
const formRef = ref(null)
const rules = {
  roleName: [
    {
      required: true,
      message: '角色名称不能为空',
      trigger: 'blur'
    },
  ]
}
const formData = toRef(props.data).value



// 打开
const open = () => {
  showDialog.value = true
  loading.value = false
  console.log(1)
  console.log(formData.value)
}
// 关闭
const close = () => showDialog.value = false
//提交
const submit = () => {
  console.log(formData)
  formRef.value.validate(async (valid) => {
    const form = { ...formData.value }
    console.log('提交的数据为:')
    console.log(form)
    loading.value = true
    if (!valid) {
      loading.value = false
      return false
    } else {
      await Role.updateRole(form).then(res => {
        console.log(res)
        if (res.data.data !== null) {
          toast('修改成功', 'success', false, 3000)
          close()
          loading.value = false
        } else {
          toast(res.data.msg, 'warning', false, 3000)
        }
        loading.value = false
      }).catch(err => {

      })
    }
  })
}

//暴露clean方法
const emit = defineEmits(["clean"])
const clean = () => {
  formRef.value.resetFields()
  emit("clean")
}

// 向父组件暴露以下方法
defineExpose({
  open,
  close
})

</script>
<style>
.formDrawer {
  width: 100%;
  height: 100%;
  position: relative;
  @apply flex flex-col;
}

.formDrawer .body {
  flex: 1;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 50px;
  overflow-y: auto;
}

.formDrawer .actions {
  height: 50px;
  @apply mt-auto flex items-center;
}
</style>